package com.imesne.assistant.jdbc.command.simple;

import com.imesne.assistant.jdbc.command.AbstractCommandExecutor;
import com.imesne.assistant.jdbc.command.CommandContext;
import com.imesne.assistant.jdbc.management.CommandTable;

import java.util.List;

/**
 * Created by liyd on 17/4/25.
 */
public abstract class AbstractSimpleCommandExecutor<T extends SimpleCommandExecutor<T>> extends AbstractCommandExecutor implements SimpleCommandExecutor<T> {

    protected String command;

    protected Object[] parameters;

    @SuppressWarnings("unchecked")
	public T command(String command) {
        this.command = command;
        return (T) this;
    }

    @SuppressWarnings("unchecked")
	public T parameters(Object[] values) {
        this.parameters = values;
        return (T) this;
    }

    public long count() {
        this.setNativeData();
        CommandContext commandContext = this.commandContextBuilder.build(this.commandTable);
        commandContext.setCommandType(CommandContext.CommandType.SELECT_OBJECT);
        return (Long) this.persistExecutor.execute(commandContext);
    }

    public Object singleResult() {
        this.setNativeData();
        CommandContext commandContext = this.commandContextBuilder.build(this.commandTable);
        commandContext.setCommandType(CommandContext.CommandType.SELECT_OBJECT);
        return this.persistExecutor.execute(commandContext);
    }

    public List<?> list() {
        this.setNativeData();
        CommandContext commandContext = this.commandContextBuilder.build(this.commandTable);
        commandContext.setCommandType(CommandContext.CommandType.SELECT_OBJECT_LIST);
        return (List<?>) this.persistExecutor.execute(commandContext);
    }

    public int update() {
        this.setNativeData();
        CommandContext commandContext = this.commandContextBuilder.build(this.commandTable);
        commandContext.setCommandType(CommandContext.CommandType.UPDATE);
        return (Integer) this.persistExecutor.execute(commandContext);
    }

    protected void setNativeData() {
        this.commandTable.addExtendData(CommandTable.ExtendDataKey.COMMAND.name(), command);
        this.commandTable.addExtendData(CommandTable.ExtendDataKey.PARAMETERS.name(), parameters);
    }
}
